package com.mzpai.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.mzpai.util.StringUtils;

public class BaseController {
	
	public static final int DEFAULT_PAGE_SIZE = 10;
    public static final int DEFAULT_PAGE_NO = 1;
    public static final int TWENTY_PAGE_SIZE = 20;
    public static final String LOGIN_COOKIE_NAME = "luc";
    protected Logger logger = LoggerFactory.getLogger(BaseController.class);
    
    
    /**
     * 前台请求参数封装成map
     *
     * @param request
     * @return
     */
    protected static Map<String, Object> searchMap(HttpServletRequest request) {
        Map<String, String[]> requestParams = request.getParameterMap();
        Map<String, Object> map = Maps.newHashMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);

            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            if (com.mzpai.util.StringUtils.isNoneBlank(valueStr)) {
                map.put(name, StringUtils.trimToNull(valueStr));
            }
        }

        return map;
    }
    
    /**
     * 清空浏览器缓存
     *
     * @param response
     */
    private void setBasicResponseHeader(HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
    }
    
    /**
     * 向界面输出内容
     *
     * @param data 输出内容
     * @throws IOException void
     * @throws
     * @since 1.0.0
     */
    protected void printWriter(HttpServletResponse response, String data) throws IOException {
        setBasicResponseHeader(response);
        response.setContentType("text/json;charset=utf-8");
        write(data, response);
    }
    
    
    private void write(String data, HttpServletResponse response) throws IOException {
        PrintWriter printWriter = response.getWriter();
        printWriter.write(data);
        printWriter.flush();
        printWriter.close();
    }


    protected void returnJson(HttpServletResponse response, String data) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        write(data, response);
    }

}
